<template>
  <div class="web-screenshot">
    <biz-project-form
      v-if="formConfig.formKey"
      id="web-screenshot-form"
      :form-config="formConfig"
      class="mb20"
      style="visibility: visible"
    />
    <el-button
      :loading="loading"
      size="default"
      type="primary"
      @click="takeScreenshot"
    >
      {{ $t("project.addOrModifyTemplateDialog.cutCoverImage") }}
    </el-button>
  </div>
</template>

<script setup>
import { ref } from "vue";
import html2canvas from "html2canvas";
import { ElMessage } from "element-plus";
import { upload } from "@/api/tool/file";
import { useI18n } from "vue-i18n";
import BizProjectForm from "@/views/formgen/components/BizProjectForm/index.vue";

const { t } = useI18n();

const props = defineProps({
  formKey: {
    type: String,
    default: ""
  }
});

const emit = defineEmits(["screenshot-taken"]);
const loading = ref(false);

const takeScreenshot = async () => {
  loading.value = true;
  try {
    // 截图
    const canvas = await html2canvas(document.getElementById("web-screenshot-form"), {
      useCORS: true,
      allowTaint: true,
      logging: false,
      scale: 1
    });

    // 转换并发送截图
    canvas.toBlob(async blob => {
      const file = new File([blob], "screenshot.png", { type: "image/png" });
      console.log(file);
      // 创建FormData对象
      const formData = new FormData();
      formData.append("file", file);

      try {
        // 调用上传接口
        const response = await upload(formData);
        console.log(response);
        // 触发事件，传递上传后的文件信息
        emit("screenshot-taken", response.data);
      } catch (error) {
        console.error("Upload failed:", error);
        ElMessage.error(t("project.addOrModifyTemplateDialog.uploadFailed"));
      }
    }, "image/png");
  } catch (error) {
    console.error("Screenshot failed:", error);
    ElMessage.error(t("project.addOrModifyTemplateDialog.screenshotFailed"));
  } finally {
    loading.value = false;
  }
};
const formConfig = ref({
  formKey: props.formKey,
  showBtns: true,
  setting: {}
});
</script>

<style scoped>
#web-screenshot-form {
  width: 900px;
  height: 100vh;
  position: absolute;
  top: -10000px;
  left: 0;
  z-index: 9999;
}
</style>
